package com.demo.web; /**
 * @author wzm
 * @create 2023-05-04 11:12
 */

import com.demo.pojo.User;
import com.demo.service.UserService;
import com.demo.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    //创建UserService对象
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //实现请求的处理和响应
        //1.设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //2.获取页面参数(返回值是String类型 如果涉及 年龄 id 需要转换类型)
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //3.将参数封装为对象
        User user = new User(username,password);

        //4.调用Service方法 传入参数进行功能的调用
        User login = userService.login(user);

        //5.判断查询结果有没有值
        if(login == null){
            //登录失败
            request.getRequestDispatcher("/login.html").forward(request,response);
            return;
        }


        if(login.getStatus() != 1){
            //账户禁用
            request.getRequestDispatcher("/login.html").forward(request,response);
            return;
        }

        //成功
        request.getRequestDispatcher("/index.jsp").forward(request,response);

    }
}
